package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Service;

import java.util.Timer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@Service
public class MyExampleSpringService implements DisposableBean {


    private static Logger log = LoggerFactory.getLogger(MyExampleForeverTask.class);

    //持有线程池对象， 服务关闭时应该关闭线程池
    private ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1024));

    private Timer timer = new Timer();



    @Override
    public void destroy() {


        try {
            shutdownExecutor();
        } catch (Exception e) {
            log.error("关闭ExecutorService失败", e);
        }

        try {
            shutdownTimer();
        } catch (Exception e) {
            log.error("关闭timer失败", e);
        }
    }

    private void shutdownTimer() {
        timer.cancel();
    }

    private void shutdownExecutor() {
        pool.shutdown(); // 停止新任务提交
        try {
            // 等正在执行的任务执行完毕
            if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // 取消当前正在执行的任务
                //等待任务取消
                if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
                    log.warn("Pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // 若当前线程在等待结束是被打断，重新取消正在执行的任务
            pool.shutdownNow();
            // Preserventerrupt status
            Thread.currentThread().interrupt();
        }
    }
}
